<?php
namespace app\bus\controller;
use think\cache\driver\Redis;
use think\Db;
use think\Controller;

class Index extends Controller
{

    public function index(){
        //访问页面
        if ($this->request->isGet()) {

            return view();
        }
        //获取请求参数
        $username = input('username');
        $password = input('password');

        //验证
        strlen($username) < 4 && $this->error('登录账号长度不能少于4位有效字符!');
        strlen($password) < 4 && $this->error('登录密码长度不能少于4位有效字符!');

        // 用户信息验证
        $user = Db::name("s_user")->where(array("account"=>$username,"password"=>$password,"status"=>"正常","is_delete"=>0))->find();

        if(empty($user)){
            wlog("用户登陆","登录失败，用户名:".$username);
            $this->error('账号或密码或用户状态不正确，请重新输入!');
        }
        $token = token();
        $redis = new Redis();
        $redis->set($user['id'],$token,60*60*120*60); // 存入session,有效期2小时
        //更新最后登陆时间
        Db::name("s_user")->where(["id"=>$user["id"]])->update(["last_login_date"=>get_date_time()]);

        session('MAP_USER', $user["id"]);

        wlog("用户登陆","登录成功，用户名:".$username);

        $url = input("url");
        if(empty($url)){
            $this->success('登录成功，正在进入系统...', "/admin");
        } else{
            $this->success('登录成功，正在进入系统...', $url);
        }
    }

    public function login(){
        //访问页面
        if ($this->request->isGet()) {
            return view();
        }

        //获取请求参数
        $username = input('username');
        $password = input('password');

        //验证
        strlen($username) < 4 && $this->error('登录账号长度不能少于4位有效字符!');
        strlen($password) < 4 && $this->error('登录密码长度不能少于4位有效字符!');

        // 用户信息验证
        $user = Db::table("s_user")->where(array("account"=>$username,"password"=>$password,"status"=>"正常"))->find();
        if(empty($user)){
            wlog("用户登陆","登录失败，用户名:".$username);
            $this->error('账号或密码或用户状态不正确，请重新输入!');
        }

        //更新最后登陆时间
        Db::table("s_user")->where(["id"=>$user["id"]])->update(["last_login_time"=>time(),"last_login_ip"=>getClientIP()]);

        session('MAP_USER', $user["id"]);

        wlog("用户登陆","登录成功，用户名:".$username);

        $url = input("url");
        if(empty($url)){
            $this->success('登录成功，正在进入系统...', "/");
        } else{
            $this->success('登录成功，正在进入系统...', $url);
        }

    }


    public function logout(){
        $user = get_user();
        $redis = new Redis();
        $redis->rm(get_user_id());
        session('MAP_USER', null);
        session_destroy();
        wlog("用户退出","退出成功，用户名:".$user["account"]);
        $this->success('退出登录成功！', '/bus');
    }

    /**
     * 返回所有用户信息
     * by xj 2018/7/25
     */
    public function user_lst(){
        $key = input('param.key');
        $key = urldecode($key);
        $arr = db("s_user")->where('name|number|account','like','%'.$key.'%')->limit(0,999999)->select();
        return json($arr);
    }


}
